package com.eastmelon.javase;

/**
* @ClassName: SynchronizedTest
* @Description: 线程同步必须同步的是同一个监视器对象
* 在案例中有一个static的方法，一个非static的方法两者不是同一个对象，要同步需要
* 使两者的字节码对象同步
* @author eastmelon
*/ 
public class SynchronizedTest {
	private void init() {
		final Outputer outputer = new Outputer();
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					try {
						Thread.sleep(10);
						outputer.output("eastmelon");
					}
					catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					try {
						Thread.sleep(10);
						Outputer.output2("hdw");
					}
					catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}

	// class Outputer{
	// public void output(String name){
	// int len=name.length();
	// synchronized (this) {//保护当前对象
	// for(int i=0;i<len;i++){
	// System.out.print(name.charAt(i));
	// }
	// System.out.println("");
	// }
	// }
	// };
	static class Outputer {
		public void output(String name) {// 保护方法
			int len = name.length();
			synchronized (Outputer.class) {
				for (int i = 0; i < len; i++) {
					System.out.print(name.charAt(i));
				}
				System.out.println("");
			}

		}

		public synchronized void output1(String name) {// 保护方法
			int len = name.length();
			for (int i = 0; i < len; i++) {
				System.out.print(name.charAt(i));
			}
			System.out.println("");
		}

		public static synchronized void output2(String name) {
			int len = name.length();
			for (int i = 0; i < len; i++) {
				System.out.print(name.charAt(i));
			}
			System.out.println("");
		}
	};

	public static void main(String[] args) {
		new SynchronizedTest().init();
	}
}
